package com.tsq.file.provider.config;

import com.alibaba.fastjson.JSON;
import com.tsq.file.api.FileInfo;
import com.tsq.file.provider.properties.FileServerProperties;
import com.tsq.file.provider.service.impl.AbstractIFileInfoService;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.tsq.file.provider.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author：dcy
 * @Description: 七牛云配置
 * @Date: 2019/9/18 13:59
 */
@Slf4j
@Configuration
@ConditionalOnProperty(name = "tsq.file-server.type", havingValue = "qiniu")
public class QiniuOSSAutoConfigure {

    @Autowired
    private FileServerProperties fileProperties;


    /**
     * 华东机房
     */
    @Bean
    public com.qiniu.storage.Configuration qiniuConfig() {
        return new com.qiniu.storage.Configuration(Zone.zone2());
    }

    /**
     * 构建一个七牛上传工具实例
     */
    @Bean
    public UploadManager uploadManager() {
        return new UploadManager(qiniuConfig());
    }

    /**
     * 认证信息实例
     *
     * @return
     */
    @Bean
    public Auth auth() {
        return Auth.create(fileProperties.getOss().getAccessKey(), fileProperties.getOss().getAccessKeySecret());
    }

    /**
     * 构建七牛空间管理实例
     */
    @Bean
    public BucketManager bucketManager() {
        return new BucketManager(auth(), qiniuConfig());
    }


    @Service
    public class QiniuOssServiceImpl extends AbstractIFileInfoService {
        @Autowired
        private UploadManager uploadManager;
        @Autowired
        private BucketManager bucketManager;
        @Autowired
        private Auth auth;

        @Override
        protected String fileType() {
            return fileProperties.getType();
        }

        @Override
        protected void uploadFile(MultipartFile file, FileInfo fileInfo,byte[] thumbByte) throws Exception {
            try {
                // 调用put方法上传
                Response response = uploadManager.put(file.getBytes(), fileInfo.getName(), auth.uploadToken(fileProperties.getOss().getBucketName()));
                fileInfo.setUrl(fileProperties.getOss().getEndpoint() + "/" + fileInfo.getName());
                fileInfo.setPath(null);
                if(null != thumbByte){
                    // 调用put方法上传 缩略图
                    uploadManager.put(thumbByte, "thumb"+fileInfo.getName(), auth.uploadToken(fileProperties.getOss().getBucketName()));
                    fileInfo.setThumbnailUrl(fileProperties.getOss().getEndpoint() + "/thumb" + fileInfo.getName());
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("上传文件异常 =",e.getMessage());
            }
        }

        @Override
        protected void uploadFile(MultipartFile file, FileInfo fileInfo) throws Exception {
            try {
                // 调用put方法上传
                uploadManager.put(file.getBytes(), fileInfo.getName(), auth.uploadToken(fileProperties.getOss().getBucketName()));
                fileInfo.setUrl(fileProperties.getOss().getEndpoint() + "/" + fileInfo.getName());
                fileInfo.setPath(null);
                fileInfo.setThumbnailUrl("");
            } catch (Exception e) {
                e.printStackTrace();
                log.error("上传文件异常 =",e.getMessage());
            }
        }

        @Override
        protected Boolean deleteFile(FileInfo fileInfo) {
            try {
                Response response = bucketManager.delete(fileProperties.getOss().getBucketName(), fileInfo.getName());
                int retry = 0;
                while (response.needRetry() && retry++ < 3) {
                    response = bucketManager.delete(fileProperties.getOss().getBucketName(), fileInfo.getName());
                }
            } catch (QiniuException e) {
                e.printStackTrace();
                log.error("删除文件异常 =",e.getMessage());
                return false;
            }
            return true;
        }

        @Override
        public Boolean downLoadFile(String fileName, HttpServletResponse response) throws IOException {
            Boolean retResult = false;
            try {
                // 获取下载文件路径
                String downloadUrl =  getDownloadUrl(fileName);
                FileUtil.download(downloadUrl,response);
            } catch (QiniuException e) {
                e.printStackTrace();
                log.error("下载文件异常 =",e.getMessage());
                return retResult;
            }
            retResult = true;
            return retResult;
        }

        /**
         * 获取下载文件路径，即：donwloadUrl
         */
        private String getDownloadUrl(String fileName) {
            //七牛云访问图片链接
            String targetUrl = fileProperties.getOss().getEndpoint() + "/" + fileName;
            String downloadUrl = auth.privateDownloadUrl(targetUrl);
            return downloadUrl;
        }
    }

}
